<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script>
        var db;
        var objectStore;

        function connectDb() {

            return new Promise(function (resolve, reject) {
                var request = window.indexedDB.open('mydb', 112);

                request.onerror = function (event) {
                    console.log('连接错误', event);
                    reject(event);
                }

                request.onsuccess = function (event) {
                    console.log(1);
                    db = request.result//可以拿到数据库对象
                    console.log(2);
                    resolve(true)
                    // addFn();
                }
                //如果指定的版本号，大于数据库的实际版本号，就会发生数据库升级事件upgradeneeded
                request.onupgradeneeded = async function (event) {
                    db = event.target.result;
                    var objectStore =  await db.createObjectStore('person', { keyPath: 'id',autoIncrement: true });
                    objectStore.createIndex('name', 'name', { unique: false });
                    objectStore.createIndex('email', 'email', { unique: false });
                    // addFn();

                    // resolve(true)

                }

            })



        }



        // connectDb();



        // setTimeout(addFn, 3000);


        function addFn() {
            return new Promise(function (resolve, reject) {
                var request = db.transaction(['person'], 'readwrite')
                .objectStore('person')
                .add({ name:"xiaohong", email: 'zhangsan@example.com' });

                request.onsuccess = function (event) {
                    console.log('数据写入成功');
                    resolve(true);
                };

                request.onerror = function (event) {
                    console.log('数据写入失败', event);
                    reject(event);
                }
            })
            
        }


        async function runDb() {
            await connectDb();
            await addFn();
        }

        runDb();

    </script>
</body>

</html>